package cn.kg.spring.factory;

import cn.kg.spring.anno.Auto;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/4/25
 * @Description:  工厂类 创建对象
 */
public class BeanFactory {

    private static Map<String,Object> map = new HashMap<>();

    static {

        ResourceBundle rb = ResourceBundle.getBundle("bean");
        //获取key
        Set<String> keys = rb.keySet();
        // 创建对象
        for (String key : keys) {
            String className = rb.getString(key);
            try {
                Class<?> clazz = Class.forName(className);
                Object o = clazz.getDeclaredConstructor().newInstance();
                map.put(key, o);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 初始化对象中属性  @Auto
        for (String key : keys) {
            String className = rb.getString(key);
            try {
                Class<?> clazz = Class.forName(className);
                Field[] declaredFields = clazz.getDeclaredFields();

                // 遍历属性 查看是否含有注解 @Auto
                for (Field declaredField : declaredFields) {
                    Auto declaredAnnotation = declaredField.getDeclaredAnnotation(Auto.class);
                    if(declaredAnnotation!=null){   // UserMapper userMapper  ->
                        // 获取属性名 从map集合中获取对应的对象
                        String name = declaredField.getName();
                        // 属性需要赋的值
                        Object o = map.get(name);
                        //  需要赋值的对象
                        Object o1 = map.get(key);
                        // 给那个是对象的属性赋什么值
                        declaredField.setAccessible(true);
                        declaredField.set(o1,o);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    //public static  UserMapper getUserMapperImpl(){
    //    return  new UserMapperImpl();
    //}


    //public static  Object  getBean(String className){
    //
    //    try {
    //        Class<?> clazz = Class.forName(className);
    //        Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
    //        declaredConstructor.setAccessible(true);
    //        Object o = declaredConstructor.newInstance();
    //        return  o;
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    }
    //    return  null;
    //}

    public static  Object  getBean(String beanName){
        Object o = map.get(beanName);
        return o ;
    }


    public static <T> T  getBean(String beanName,Class<T> clazz){

        Object o = map.get(beanName);
        return  clazz.cast(o);
    }


}
